var SM = {};
module.exports = SM;

var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
    host: 'localhost:9200',
    // log: 'trace'
});

// console.log('--- elasticsearch ---', elasticsearch)
// console.log('--- client ---', client)


var my_index = 'medic';

var my_doc_type = 'dicom';

// ["disease_name", "dept", "modality", "age", "gender", "physician", "location", "character"]

//高亮匹配的词
var highlight = {
    "pre_tags": ["<em class='em-label' style='color:#212121'>", "<em class='em-label' style='color:#212121>"],
    "post_tags": ["</em>", "</em>"],
    "fields": {
        "content": {}
    }
};

function getNormalSearch(query) {
    var normalSearch = [
        {
            match: {
                "character": {
                    query: query,
                    minimum_should_match: "50%",
                    boost: 3
                }
            }
        },
        {
            match: {
                "disease_name": {
                    query: query,
                    "boost": 2,
                    minimum_should_match: "50%"
                }

            }
        },
        {
            match: {
                "dept": {
                    "query": query,
                    "minimum_should_match": "50%"
                }

            }
        },
        {
            match: {
                "physician": {
                    query: query,
                    "minimum_should_match": "50%"
                }

            }
        },
        {
            match: {
                "content": {
                    query: query,
                    minimum_should_match: "50%"
                }

            }
        },
        {
            match: {
                "location": {
                    query: query,
                    minimum_should_match: "50%"
                }

            }
        }
    ]
    return normalSearch
}

//提供搜索功能
SM.search = function (search, pageNum, perPage, callback) {

    var body = {
        query: {
            bool: {
                should: getNormalSearch(search['query']),
                minimum_should_match: 1
            }
        },
        highlight: highlight
    };

    var searchParams = {
        index: my_index,
        type: my_doc_type,
        from: pageNum,
        size: perPage,
        body: body
    };
    finalSearchParams(searchParams, pageNum, perPage, callback);
    // client.search(searchParams).then(function (resp) {
    //     var hits = resp.hits.hits;
    //     var pages = Math.ceil(res.hits.total / perPage)
    //     res['id'] = 1;
    //     res['from'] = pageNum;
    //     res['pages'] = pages;
    //     res['hits'] = hits;
    //     callback(res);
    // }, function (err) {
    //     console.trace(err.message);
    //     res['id'] = 0;
    //     callback(res);
    //
    // });
};

function finalSearchParams(searchParams, pageNum, perPage, callback) {
    var res = {};
    client.search(searchParams, function (error, response) {
        console.log('--- response --- ', response);
        console.log('--- error --- ', typeof (error));
        if (response) {
            var hits = response.hits.hits;
            var pages = Math.ceil(response.hits.total / perPage)
            res['id'] = 1;
            res['from'] = pageNum;
            res['pages'] = pages;
            res['hits'] = hits;
            callback(res);
        } else {
            res['id'] = 0;
            callback(res);
        }
    });
}


//搜索全部
SM.searchAll = function (pageNum, perPage, callback) {
    var body = {};

    var searchParams = {
        index: my_index,
        type: my_doc_type,
        from: pageNum,
        size: perPage,
        body: body
    };

    finalSearchParams(searchParams, pageNum, perPage, callback);
    // client.search(searchParams, function (error, response) {
    //     console.log('--- response --- ', response);
    //     if(error){
    //         var hits = response.hits.hits;
    //         var pages = Math.ceil(res.hits.total / perPage)
    //         res['id'] = 1;
    //         res['from'] = pageNum;
    //         res['pages'] = pages;
    //         res['hits'] = hits;
    //         callback(res);
    //     }else{
    //         res['id'] = 0;
    //         callback(res);
    //     }
    // });

    //     .then(function (resp) {
    //     console.log('--- resp --- ');
    //     var hits = resp.hits.hits;
    //     var pages = Math.ceil(res.hits.total / perPage)
    //     res['id'] = 1;
    //     res['from'] = pageNum;
    //     res['pages'] = pages;
    //     res['hits'] = hits;
    //     callback(res);
    //
    // }, function (err) {
    //     // console.trace(err.message);
    //     console.log('--- err --- ');
    //     res['id'] = 0;
    //     // return res;
    //     callback(res);
    //
    // });
};


SM.search_plus = function (searchData, callback) {
    var pageNum = request.params.page;
    var perPage = request.params.per_page;
    var userQuery = request.params.search_query;
    var userId = request.session.userId;

    var searchParams = {
        index: 'posts',
        from: (pageNum - 1) * perPage,
        size: perPage,
        body: {
            query: {
                filtered: {
                    query: {
                        match: {
                            // match the query against all of
                            // the fields in the posts index
                            _all: userQuery
                        }
                    },
                    filter: {
                        // only return documents that are
                        // public or owned by the current user
                        or: [
                            {
                                term: {privacy: "public"}
                            },
                            {
                                term: {owner: userId}
                            }
                        ]
                    }
                }
            }
        }
    };

    client.search(searchParams, function (err, res) {
        if (err) {
            // handle error
            throw err;
        }

        response.render('search_results', {
            results: res.hits.hits,
            page: pageNum,
            pages: Math.ceil(res.hits.total / perPage)
        });
    });
};


SM.searchAll(0, 10, function (res) {
    console.log('--- res ---', res);
});
// console.log('--- data ---', data);
// var search = {"query": "李四"};
//
// SM.search(search, 0, 10, function (res) {
//     console.log('--- res ---', res.id);
// });